require 'rake/dsl_definition'
require 'yaml'

namespace :OSDD do
  desc "OSDD installer"
  task :install do 

    begin
      puts " "

      if ENV['host'].nil? or ENV['host'] == ''

        puts "The 'host' attribute is mandatory"
        puts "Exiting.."
      elsif ENV['username'].nil? or ENV['username'] == ''

        puts "The 'username' attribute is mandatory"
        puts "Exiting.."
      elsif ENV['password'].nil? or ENV['password'] == ''

        puts "The 'password' attribute is mandatory"
        puts "Exiting"
      else

        host      = ENV['host']
        username  = ENV['username']
        password  = ENV['password']

        puts "---------------------------------"
        puts "Starting to install OSDD.. wait.."
        puts " "

        # puts "-- Installing the gems.."
        # system("sudo bundle install")
        # puts " "
        # puts "-- All gems installed!"
        # puts " "

        puts "-- Creating the database file.."
        yaml = YAML.load_file('config/database.sample.yml')

        yaml['development']['username'] = username
        yaml['development']['password'] = password
        yaml['development']['host']     = host
        
        yaml['test']['username']        = username
        yaml['test']['password']        = password
        yaml['test']['host']            = host

        yaml['production']['username']  = username
        yaml['production']['password']  = password
        yaml['production']['host']      = host

        if File.open('config/database.yml', 'w') {|f| f.write(yaml.to_yaml)}
          scn_database_file = username + ":" + password  

          File.open('config/databaseScn', 'w') {|f| f.write(scn_database_file)}

          puts "-- Database file created!"
          puts " "

          puts "-- Creating the PostgreSQL database.."
          system('rake db:create')
          puts "-- Database created!"
          
          puts " "
          puts "-- Generating the database schema.."
          puts "Please enter the user root password.."
          system('sudo su postgres --command "psql -U postgres -d OSDD -f structure.sql"')

          puts "Database schema generated!"
          puts " "

          puts "-- Creating the admin user.."
          system('rake db:seed')
          puts "-- Admin user created!"
          puts " "

          puts "-----------------------------------------------------------"
          puts " "
          puts "The installation is complete. Thank's for using OSDD!"
          puts "-----------------------------------------------------------"
          puts "Remember that the OSDD project is Open Source,"
          puts "visit http://code.google.com/p/osdd/ for more information."
          puts " "
          puts "INFO Now run localhost:3000 in your browser"
          puts "-----------------------------------------------------------"
          puts " "
        end
      end
    rescue SyntaxError, NameError => error
      puts error
    end
  end
end
